﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace Having.Site.Route
{
    /// <summary>
    /// 页面级路由基础类
    /// </summary>
    public class LocalPageRoute
    {
        /// <summary>
        /// 本地的地址，如/abc/abc.cshtml，也可以使用*.cshtml表示当前文件夹下的全部文件
        /// </summary>
        public string LocalPage { set; get; }
        /// <summary>
        /// 虚拟路径的模板，含有正则的路由( /{a:regex([0-9]+)})或者不含正则的路由（/{a}），（也可以使用abc*来表示全部文件的路由前面加abc，跟*.cshtml对应）
        /// </summary>
        public string RelativeTemplate { set; get; }
        /// <summary>
        /// 含有表达式的路由(主要给到程序解析)
        /// </summary>
        public string Template { get; }
        /// <summary>
        /// RelativeTemplate对应的url的内部类,例如{a="\w+",b="\d+"}
        /// </summary>
        public Object reg { set; get; }

        /// <summary>
        /// 处理的结果
        /// </summary>
        public RequestDelegate action { set; get; }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="LocalPage">本地的地址，如/abc/abc.cshtml</param>
        /// <param name="RelativeTemplate">虚拟路径的模板,(正则的{}要换成{{}})</param>
        /// <param name="action">操作</param>
        public LocalPageRoute(string LocalPage, string RelativeTemplate, Object reg=null, RequestDelegate action=null)
        {
            this.action = action;
            this.LocalPage = LocalPage;
            this.RelativeTemplate = RelativeTemplate;
            this.reg = reg;
            this.Template = this.RelativeTemplate;
            if (RelativeTemplate != null)
            {
                if (reg != null)
                {
                    var pis = reg.GetType().GetProperties();
                    var sp = this.RelativeTemplate;
                    foreach (var pi in pis)
                    {
                        sp = sp.Replace("{" + pi.Name + "}", "{" + pi.Name + ":regex(^" + pi.GetValue(reg).ToString().Replace("{", "{{").Replace("}", "}}") + "$)}");
                    }
                    this.Template = sp;
                }
            }
            
        }
    }
}
